package com.shengcheng.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shengcheng.constant.KafkaConstant;
import com.shengcheng.constant.SystemConstant;
import com.shengcheng.entity.AlbumStat;
import com.shengcheng.entity.TrackStat;
import com.shengcheng.service.AlbumStatService;
import com.shengcheng.service.TrackStatService;
import com.shengcheng.vo.TrackStatMqVo;
import com.shengcheng.vo.TrackStatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AlbumConsumer {

    @Autowired
    private TrackStatService trackStatService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AlbumStatService albumStatService;

    @KafkaListener(topics = KafkaConstant.UPDATE_TRACK_STAT_QUEUE)
    public void updateStat(String dataJson){
        TrackStatMqVo trackStatMqVo = JSON.parseObject(dataJson, TrackStatMqVo.class);

        String key = trackStatMqVo.getBusinessNo();
        //防止重复消费
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(key, 1, 20, TimeUnit.SECONDS);
        if(isExist){
            String statType = trackStatMqVo.getStatType();
            LambdaQueryWrapper<TrackStat> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TrackStat::getTrackId, trackStatMqVo.getTarckId())
                    .eq(TrackStat::getStatType,statType);
            TrackStat trackStat = trackStatService.getOne(wrapper);
            trackStat.setStatNum(trackStat.getStatNum()+trackStatMqVo.getCount());
            trackStatService.updateById(trackStat);

            //如果是专辑，跟新专辑播放量
            if(statType.equals(SystemConstant.PLAY_NUM_TRACK)){
                LambdaQueryWrapper<AlbumStat> albumStatLambdaQueryWrapper = new LambdaQueryWrapper<>();
                albumStatLambdaQueryWrapper.eq(AlbumStat::getAlbumId,trackStatMqVo.getAlbumId())
                        .eq(AlbumStat::getStatType,SystemConstant.PLAY_NUM_ALBUM);
                AlbumStat albumStat = albumStatService.getOne(albumStatLambdaQueryWrapper);
                albumStat.setStatNum(albumStat.getStatNum()+trackStatMqVo.getCount());
                albumStatService.updateById(albumStat);
                //更新es里数据
            }
        }


    }






}
